<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use \think\Db;
use \think\Cookie;
use think\Loader;
use app\admin\model\Cla as claModel;//班级信息模型
use app\admin\model\AdminMenu;
use app\admin\controller\User;
class Cla extends User
{
    /**
     * 班级信息列表
     * @return [type] [description]
     */
    public function index()
    {
        //实例化班级模型
        $model = new claModel();
        $cname='';
        $post = $this->request->post();
        if (isset($post['xid']) and $post['xid'] > 0) {
            $where['xid'] = $post['xid'];
        }
        if (isset($post['cname']) and !empty($post['cname'])) {
            $where['cname'] = ['like', '%' . $post['cname'] . '%'];
            $cname=$post['cname'];
        }
        $cla = empty($where) ? $model::with(['stu','stu.reason'])->order('cid asc')->paginate(4) : $model->where($where)->order('cid asc')->paginate(4);
      //    echo Db()->getLastSql();

      //    print_r($cla);
      //    dump($cla);
      // die;
        $school=Db::name("school")->select();
        $this->assign('school',$school);
        $this->assign('cla',$cla);
        $this->assign('cname',$cname);
       return $this->fetch();
    }
    /**
     * 班级的添加及修改
     * @return [type] [description]
     */
    public function publish()
    {
        //获取班级id
        $cid = $this->request->has('cid') ? $this->request->param('cid', 0, 'intval') : 0;
        $model = new claModel();
        if($cid > 0) {
            //是修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['cname', 'require', '班级名称不能为空'],
                    ['xid', 'require','必须选择学校']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证学校名是否存在
                $xname = $model->where(['cname'=>$post['cname'],'xid'=>$post['xid']])->select();
                if(!empty($xname)) {
                    return $this->error('提交失败：已经存在该班级');
                }
                if(false == $model->allowField(true)->save($post,['cid'=>$cid])) {
                    return $this->error('修改失败');
                } else {
                    //addlog($model->id);//写入日志
                    return $this->success('修改班级信息成功','admin/cla/index');
                }
            } else {
                //非提交操作
                $info['cla'] = $model->where('cid',$cid)->find();
                $info['school']=Db::name("school")->select();
                $this->assign('info',$info);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['cname', 'require','班级名称不能为空'],
                    ['xid', 'require','必须选择学校']
                ]);
                //验证该班级是否存在
                $name = $model->where(['cname'=>$post['cname'],'xid'=>$post['xid']])->select();
                if(!empty($name)) {
                    return $this->error('提交失败：已经存在该班级');
                }
                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加班级失败');
                } else {
                    //addlog($model->id);//写入日志
                    return $this->success('添加班级成功','admin/cla/index');
                }
            } else {
                //非提交操作
                $info['school']=Db::name("school")->select();
                $this->assign('info',$info);
                return $this->fetch();
            }
        }
    }
    /**
     * 班级删除
     * @return [type] [description]
     */
    public function delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('cla')->where('cid',$id)->delete()) {
                return $this->error('删除失败');
            } else {
                //addlog($id);//写入日志
                return $this->success('删除成功','admin/cla/index');
            }
        }
    }
     function excel()
      {
           ini_set('memory_limit','1024M');
    Loader::import('PHPExcel.Classes.PHPExcel');
    header("content-type:text/html;charset=utf8");
    $objExcel = new \PHPExcel();
    $objSheet = $objExcel -> getActiveSheet();
    $objSheet -> setTitle("PHPExcel导出测试");
    $data = Db::name('cla') -> select();
    $objSheet -> setCellValue('A1','ID')
            -> setCellValue('B1','姓名');
    $j = 2;
    foreach ($data as $k => $v){
        $objSheet -> setCellValue('A'.$j,$v['cid'])
            -> setCellValue('B'.$j,$v['cname']);
        $j++;
    }
    $file_name = '文件名'.'xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header("Content-Disposition: attachment;filename=$file_name");
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
    header ('Cache-Control: cache, must-revalidate');
    header ('Pragma: public'); 

    $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
    $objWriter->save('php://output');
    exit;
     }
     
}
?>